package com.yz.javaagent.agent;

import java.io.File;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;


public class JavaAgent {

    /**
     * attach 方式启动
     * @param args
     * @param inst
     * @throws Exception
     */
    public static void agentmain(String args, Instrumentation inst) throws Exception {
        System.out.println("args:"+args);
        String[] split = args.split(",");
        String coreJarPath = split[0];
        String className = split[1];
        String methodName = split[2];
        inst.appendToBootstrapClassLoaderSearch(new JarFile(coreJarPath));
        ClassLoader classLoader = JavaAgent.class.getClassLoader();
        Class<?> aClass1 = classLoader.loadClass("com.yz.javaagent.core.transformer.ClassUtil");
        byte[] fileByte = (byte[]) aClass1.getMethod("getClassFileByte", String.class,String.class).invoke(null, className,methodName);
        ClassDefinition classDefinition = new ClassDefinition(classLoader.loadClass(className),fileByte);
        //attach 方式时使用
        inst.redefineClasses(classDefinition);
    }

    /**
     * onload 启动前运行
     * @param args
     * @param instrumentation
     */
    public static void premain(String args,Instrumentation instrumentation) {
        //onload时使用
        instrumentation.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
                return new byte[0];
            }
        });
    }

}
